import Vue from 'vue'
import VueRouter from 'vue-router'
import jwt from 'jsonwebtoken'

Vue.use(VueRouter)

// 导入组件
const Login = () => import('../views/Login.vue')
const App = () => import('../views/App.vue')
const Register = () => import('../views/Register.vue')
const Dashboard = () => import('../views/Dashboard.vue')
const Admin = () => import('../views/Admin.vue')
const ProductCate = () => import('../views/ProductCate.vue')
const Carousel = () => import('../views/Carousel.vue')
const Role = () => import('../views/Role.vue')
const Products = () => import('../views/Products.vue')

const router = new VueRouter({
  linkActiveClass: 'active',
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    {
      path: '/app',
      component: App,
      children: [
        { path: '/', redirect: '/app/dashboard' },
        { path: 'dashboard', component: Dashboard },
        { path: 'admin', component: Admin },
        { path: 'productcate', component: ProductCate },
        { path: 'product', component: Products },
        { path: 'role', component: Role },
        { path: 'carousel', component: Carousel }
      ]
    }
  ]
})
router.beforeEach((to, from, next) => {
  // 获取存在本地的token
  const token = localStorage.getItem('ZY-Token')
  let valid = true
  try {
    jwt.verify(token, '0401')
  } catch (err) {
    valid = false
  }
  // 当路由地址为登录页面，且已登录。跳转到app页面
  if (to.path === '/login' && valid) {
    next('/app')
  } else if (/^(\/app)/i.test(to.path)) { // 当路径包含/app,一定需要判断是否登录
    if (valid) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router
